package com.qf.blog.service.impl;

import com.qf.blog.core.dao.IBaseDao;
import com.qf.blog.core.service.BaseServiceImpl;
import com.qf.blog.core.utils.PasswordUtils;
import com.qf.blog.core.utils.UUIDUtils;
import com.qf.blog.dao.IUserDao;

import com.qf.blog.entity.UserEntity;
import com.qf.blog.mybatis.SqlSessionThreadLocal;
import com.qf.blog.service.IUserService;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;

public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements IUserService {

    @Override
    protected IBaseDao<UserEntity> getBaseDao() {
        SqlSession sqlSession = SqlSessionThreadLocal.get();
        return sqlSession.getMapper(IUserDao.class);
    }

    @Override
    public void register(UserEntity userEntity) throws Exception {
        IUserDao baseDao = (IUserDao) getBaseDao();
        //密码加密
        userEntity.setPassword(PasswordUtils.hashPw(userEntity.getPassword()));
        //设置用户状态
        userEntity.setStatus(1);
        userEntity.setCreateTime(new Date());
        userEntity.setActivationCode(UUIDUtils.getId());
        userEntity.setType(0);
        //入库
        int save = baseDao.insert(userEntity);
    }

    @Override
    public UserEntity byActivationCode(String activationCode) throws Exception {
        IUserDao baseDao = (IUserDao) getBaseDao();
        return baseDao.selectByActivationCode(activationCode);
    }

    @Override
    public UserEntity login(String username, String password) throws Exception {
        IUserDao baseDao = (IUserDao) getBaseDao();
        // 1.根据用户用户名查询
        UserEntity userEntity = baseDao.selectByUsername(username);
        if (userEntity==null){
            return null;
        }
        // 2、密码的比对
        if (!PasswordUtils.check(password,userEntity.getPassword())){
            return null;
        }
        return userEntity;
    }

    @Override
    public void updateHeaderUrl(Integer id, String filePath) throws Exception {
        IUserDao baseDao = (IUserDao) getBaseDao();
        baseDao.updateHeaderUrl(id,filePath);
    }

}
